package com.sxz.sbs.module.sale;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.sxz.sbs.R;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.applibrary.component.ClearEditText;
import com.sxz.sbs.applibrary.state.StateLayout;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.constant.IntentConstant;
import com.sxz.sbs.event.AlterStallDetailEvent;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.sale.adapter.SaleControlStallAdapter;
import com.sxz.sbs.module.sale.mode.StallListBean;
import com.sxz.sbs.module.sale.presenter.SaleControlStallPresenter;
import com.sxz.sbs.module.sale.view.SaleControlStallView;
import com.sxz.sbs.router.RouterUrl;
import com.sxz.sbs.widget.CommonTitle;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 销控车位 列表
 */
@Route(path = RouterUrl.SALE_CONTROL_STALL)
public class SaleControlStallActivity extends BaseActivity<SaleControlStallPresenter> implements SaleControlStallView {
    @Autowired(name = IntentConstant.SALE_CONTROL_BUILD_NAME)
    String parkingName ;
    @Autowired(name = IntentConstant.SALE_CONTROL_BUILD_ID)
    int parkingId ;
    @Autowired
    int from;
    @Autowired
    int customId;
    @BindView(R.id.cet_relate_stall_search)
    ClearEditText cetSearch;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.stateLayout)
    StateLayout stateLayout;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    private int currentPage = 1;
    private List<StallListBean.ListBean> dataList = new ArrayList<>();
    private SaleControlStallAdapter adapter;
    @Override
    protected void init() {
        ARouter.getInstance().inject(this);
        EventBus.getDefault().register(this);
        new CommonTitle.Builder(this).setTitle(parkingName).build().show();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        refreshLayout.setColorSchemeResources(R.color.color_main);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                getStallList();
            }
        });
        refreshLayout.setRefreshing(true);
        getStallList();
        adapter = new SaleControlStallAdapter(dataList,from);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (from ==1) {
                    HashMap<String,Object> map = HttpParamMap.getParamMap();
                    map.put("parkSpaceId",dataList.get(position).getId());
                    map.put("customId",customId);
                    mPresenter.addIntentStall(map);
                } else {
                    startActivity(new Intent(SaleControlStallActivity.this,
                            StallDetailActivity.class).putExtra("stall_id",dataList.get(position).getId()));
                }

            }
        });
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                currentPage ++;
                getStallList();
            }
        },recyclerView);
        cetSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager imm = (InputMethodManager) v.getContext()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive())
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    currentPage = 1;
                    getStallList();
                    return true;
                }
                return false;
            }
        });
        stateLayout.setOnRetryListener(new StateLayout.OnRetryListener() {
            @Override
            public void onRetry(int state) {
                getStallList();
            }
        });
    }

    /**
     * 获取车位列表
     */
    private void getStallList () {
        HashMap<String,Object> map = HttpParamMap.getParamMap();
        map.put("parkingId", parkingId);
        map.put("txt", cetSearch.getInputValue());
        map.put("pageNumber", currentPage);
        map.put("pageSize", AppConstant.PAGE_SIZE);
        mPresenter.getStallList(map);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_relate_stall;
    }

    @Override
    protected SaleControlStallPresenter createPresenter() {
        return new SaleControlStallPresenter();
    }

    @Override
    public void onGetStallListSuccess(StallListBean bean) {
        if (mIsLive && bean != null) {
            refreshLayout.setRefreshing(false);
            if (bean.getList() != null && bean.getList().size() >0 ) {
                stateLayout.showContent();
                if (currentPage == 1) {
                    dataList.clear();
                    dataList.addAll(bean.getList());
                    adapter.notifyDataSetChanged();
                } else {
                    dataList.addAll(bean.getList());
                    adapter.notifyDataSetChanged();
                }
                adapter.loadMoreComplete();
            } else {
                if (currentPage == 1) {
                    dataList.clear();
                    adapter.notifyDataSetChanged();
                    //  数据为空
                    stateLayout.showEmpty();
                } else {
                    adapter.loadMoreEnd();
                }
            }

        }
    }

    @Override
    public void onAddIntentStallSuccess() {
        finish();
    }

    @Override
    public void showError(int errorTag, String msg) {
        refreshLayout.setRefreshing(false);
        if (currentPage == 1) {
            if (errorTag == AppConstant.NET_ERROR_CODE) {
                stateLayout.showNetwork();
            } else {
                stateLayout.showEmpty();
            }
        } else {
            adapter.loadMoreFail();
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAlterDetailEvent(AlterStallDetailEvent event) {
        currentPage = 1;
        getStallList();
    }
    @Override
    public void loginAgain() {
        super.loginAgain();
        refreshLayout.setRefreshing(false);
        adapter.loadMoreFail();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
